package report

import (
	"fmt"

	"github.com/shirou/gopsutil/v3/disk"
	"gopkg.in/yaml.v2"
)

type DiskSummary struct {
	Size        uint64  `json:"size" yaml:"size"`
	Used        uint64  `json:"used" yaml:"used"`
	Free        uint64  `json:"free" yaml:"free"`
	UsedPercent float64 `json:"percent" yaml:"percent"`
	Count       int     `json:"count" yaml:"count"`
}
type DiskInfo struct {
	Path              string  `json:"path" yaml:"path"`
	Fstype            string  `json:"fstype" yaml:"fstype"`
	Total             uint64  `json:"total" yaml:"total"`
	Free              uint64  `json:"free" yaml:"free"`
	Used              uint64  `json:"used" yaml:"used"`
	UsedPercent       float64 `json:"usedPercent" yaml:"usedPercent"`
	InodesTotal       uint64  `json:"inodesTotal" yaml:"inodesTotal"`
	InodesUsed        uint64  `json:"inodesUsed" yaml:"inodesUsed"`
	InodesFree        uint64  `json:"inodesFree" yaml:"inodesFree"`
	InodesUsedPercent float64 `json:"inodesUsedPercent" yaml:"inodesUsedPercent"`
}

func FetchDiskInfo() []DiskInfo {
	var diskInfoList []DiskInfo

	partitions, err := disk.Partitions(false)
	if err != nil {
		return nil
	}
	for _, partition := range partitions {
		usage, err := disk.Usage(partition.Mountpoint)
		if err != nil {
			continue
		}
		diskInfoList = append(diskInfoList, DiskInfo{
			Path:              partition.Mountpoint,
			Fstype:            partition.Fstype,
			Total:             usage.Total,
			Free:              usage.Free,
			Used:              usage.Used,
			UsedPercent:       usage.UsedPercent,
			InodesTotal:       usage.InodesTotal,
			InodesUsed:        usage.InodesUsed,
			InodesFree:        usage.InodesFree,
			InodesUsedPercent: usage.InodesUsedPercent,
		})

	}
	return diskInfoList
}

func (d *DiskInfo) Show() {
	// fmt.Printf("Disk: %v\n", d)
	out, err := yaml.Marshal(d)
	if err != nil {
		return
	}

	fmt.Printf("disk : %v\n", string(out))
}

func ShowDiskSummary(disks []DiskInfo) {

	for _, disk := range disks {
		// fmt.Printf("Disk: %v\n", disk)
		disk.Show()
	}
}

func FetchDiskSummary(disks []DiskInfo) DiskSummary {
	var diskSummary DiskSummary
	for _, disk := range disks {
		diskSummary.Size += disk.Total
		diskSummary.Used += disk.Used
		diskSummary.Free += disk.Free
		diskSummary.UsedPercent += disk.UsedPercent
		diskSummary.Count++
	}
	return diskSummary
}
